package edu.scut.yi.yx.processer;

import java.sql.SQLException;

import com.electrotank.electroserver5.extensions.api.PluginApi;
import com.electrotank.electroserver5.extensions.api.value.EsObjectEntry;
import com.electrotank.electroserver5.extensions.api.value.EsObjectRO;
import com.electrotank.electroserver5.extensions.api.value.EsObject;

import edu.scut.yi.yx.lobbymanager.Command;
import edu.scut.yi.yx.dbmanager.DatabaseJDBCPlugin;

public class LoadBuddiesProcesser extends AbstractProcesser{
	
	private DatabaseJDBCPlugin databaseJDBCPlugin;
	private EsObject loadFinish;

	@Override
	public String getCommand() {
		// TODO Auto-generated method stub
		return Command.LoadBuddies.getCode();
	}

	@Override
	public void process(String user, EsObjectRO message, PluginApi api) {
		// TODO Auto-generated method stub
		databaseJDBCPlugin = (DatabaseJDBCPlugin)api.getServerPlugin("DatabaseJDBCPlugin");
		try{
		EsObject result = databaseJDBCPlugin.doQuery("SELECT buddy FROM buddylist WHERE username = "+"'"+user+"'");
		api.getLogger().debug("buddy result "+result);
		for(int i=0; i<result.getEsObjectArray("results").length; i++){
			String buddyname = result.getEsObjectArray("results")[i].getString("buddy");
			boolean su = api.addBuddy(user, buddyname, null);
			api.getLogger().debug("is add success"+ su);
			api.getLogger().debug("add buddy "+buddyname);
		}
		api.getLogger().debug("buddies "+api.getBuddies(user));
		loadFinish = new EsObject();
		loadFinish.setString(Command.Action.getCode(), Command.LoadBuddies.getCode());
		loadFinish.setString(Command.State.getCode(), Command.Success.getCode());
		loadFinish.setEsObject(Command.Message.getCode(), result);
		}catch(SQLException e){
			e.printStackTrace();
		}
		// MessagingHelper.sendSuccessMessage(Command.LoadBuddies, user, results, api);
		
		api.sendPluginMessageToUser(user, loadFinish);
	}

}
